package com.matrix.hellokafka.producerSendType;

import com.matrix.hellokafka.util.ConfigUtil;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Objects;
import java.util.Properties;

public class KafkaAsyncProduct {

    public static void main(String[] args) {
        Properties properties = ConfigUtil.getProducerProperties();

        KafkaProducer<String, String> producer = new KafkaProducer<String, String>(properties);

        try {
            ProducerRecord<String, String> record;
            for (int i = 0; i < 400; i++) {
                record = new ProducerRecord<>("my-topict", String.valueOf(i), "jyy==>"+i);

                //异步模式发送消息
                producer.send(record, new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata recordMetadata, Exception exception) {
                        if(Objects.nonNull(exception)){
                            exception.printStackTrace();
                        }
                        if(Objects.nonNull(recordMetadata)){
                            System.out.println(String.format("offset:%s,partition:%s,topic:%s",recordMetadata.offset(),recordMetadata.partition(),recordMetadata.topic() ));
                        }
                    }
                });
                System.out.println(i + "，message is sent");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            producer.close();
        }
    }
}
